<?php
namespace App\Admin\Controllers\Inventory;

use App\Importer\Inventory\CNImporter;
use App\Models\Basics\SysArea;
use App\Models\Inventory\AdjustArea;
use App\Models\Inventory\AreaCn;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class AdjustAreaUploadController extends AdminController{

    protected $title = '站点库存调整';

    protected function grid()
    {
        return view('inventory.adjust-area-upload.index');
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new CNImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $num = $row[2] ? trim($row[2]) : 0;
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $key = $_area.'-'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($num)){
                    $errors[$count] = '数量格式有误';
                    break;
                }
                if($num < 0){
                    $errors[$count] = '数量不能小于0';
                    break;
                }
                $area = strtoupper($_area);
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $inventory = AreaCn::query()
                    ->where('area_id',$areaId)
                    ->where('psku_id',$pSkuId)
                    ->lockForUpdate()
                    ->first();
                if(!$inventory){
                    $errors[$count] = $key.'库存不存在';
                    continue;
                }
                $tempInstant = $inventory->instant;
                $inventory->instant = $num;
                $flag = $inventory->save();
                if(!$flag){
                    DB::rollBack();
                    continue;
                }
                $adjustArea = AdjustArea::query()->create(
                    [
                        'area_id' => $areaId,
                        'psku_id' => $pSkuId,
                        'b_num' => $tempInstant,
                        'a_num' => $num,
                        'auser_id' => $userId
                    ]
                );
                if(!$adjustArea){
                    DB::rollBack();
                    continue;
                }else{
                    DB::commit();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
